package com.yanqu.road.server.manager.douluodalu.impl;

import com.yanqu.road.entity.activity.douluodalu.DouLuoDaLuUserEvent;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuEventInfo;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuRegionInfo;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuHelpRecordData;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuUserData;
import com.yanqu.road.entity.log.cross.LogDouLuoDaLuHunHuan;
import com.yanqu.road.entity.log.cross.LogDouLuoDaLuKill;
import com.yanqu.road.server.manager.douluodalu.*;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;
import java.util.Random;

/**
 * 魂兽事件处理
 */
public class DouLuoDaLuMonsterFightEventAction extends DouLuoDaLuBaseFightEventAction implements IDouLuoDaLuUserEventAction {


    public DouLuoDaLuMonsterFightEventAction(CrossDouLuoDaLuContext context, DouLuoDaLuEventInfo eventInfo) {
        super(context, eventInfo);
    }

    /**
     * 生成魂兽事件，按区域生成动态血量
     * monsterId 只是用于形象
     */
    @Override
    public DouLuoDaLuEventResult init0() {
        DouLuoDaLuEventResult eventResult = new DouLuoDaLuEventResult();
        //随机魂兽形象
        int monsterId;
        Random random = new Random();
        List<Integer> monsterList = StringUtils.stringToIntegerList(eventInfo.getTargetId(), "\\|");
        if(monsterList.size() == 1){
            monsterId = monsterList.get(0);
        }else {
            int idx = random.nextInt(monsterList.size());
            monsterId = monsterList.get(idx);
        }

        if(!context.getActivity().getNpcBlood().containsKey(eventInfo.getEventId())){
            context.getActivity().initMonsterDynamicBlood(false);
        }

        //不同事件,魂兽血量不同
        long ability = context.getActivity().getNpcBlood(eventInfo.getEventId());

        DouLuoDaLuUserEvent event = new DouLuoDaLuUserEvent();
        event.setTotalBlood(ability);
        event.setBlood(ability);
        event.setEventId(eventInfo.getEventId());
        event.setEventType(eventInfo.getEventType());
        event.setMonsterId(monsterId);
        event.setRegionId(context.getUserData().getRegionId());
        event.setAddTime(DateHelper.getCurrentSecond());
        context.getUserData().setEvent(event);
        eventResult.setUserEvent(event);
        return eventResult;
    }

    /**
     * 攻击怪物：每个人标记的怪物不共享血量，所以生成的每个怪物只有一条协助记录；
     * 攻击未标记的怪物，对事件加锁，扣事件血量
     * 击杀未标记的怪物，对事件加锁，事件完成，发奖
     * 攻击已标记的怪物，对协助记录加锁，扣协助记录血量，扣事件血量
     * 击杀已标记的怪物，对协助记录加锁，协助记录取消，事件完成，发奖
     * @param action 1:攻击；2：标记；3：绕过
     */
    @Override
    public DouLuoEventHandleResult handle0(int action, byte[] params) {
        DouLuoEventHandleResult handleResult = super.handle0(action, params);
        if(handleResult.getRet() != 0){
            return handleResult;
        }
        handleResult.setEventId(eventInfo.getEventId());
        DouLuoDaLuUserData userData = context.getUserData();
        DouLuoDaLuUserEvent event = userData.getEvent();
        handleResult.setUserEvent(event);
        if (!CrossDouLuoDaLuMgr.hasEvent(event)) {
            handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_USER_NOT_EVENT);
            return handleResult;
        }
        DouLuoDaLuRegionInfo regionInfo = context.getActivity().getConfig().getRegionInfo(userData.getRegionId());
        DouLuoDaLuEventInfo eventInfo = context.getActivity().getEventInfo(event.getEventId());
        //总血量
        long totalBlood;
        //奖励
        Property hunHuan = new Property();
        Property goodsProperty = new Property();
        if(action == 1) {
            //伤害buff先用再扣
            long attack = CrossDouLuoDaLuMgr.getHunLiDamageAddBuff(context, userData);
            if(event.getStatus() == 2){
                //攻击已标记过（攻击自己标记的魂兽）
                DouLuoDaLuHelpRecordData helpRecordData = userData.getCurrentHelpRecordData();
                if(helpRecordData == null){
                    handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                    //清理事件
                    userData.setEvent(new DouLuoDaLuUserEvent());
                    return handleResult;
                }

                //双重验证
                if(userData.getCurrentHelpRecordData() == null || helpRecordData != userData.getCurrentHelpRecordData()){
                    //协助已被队友完成
                    handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                    //清理事件
                    userData.setEvent(new DouLuoDaLuUserEvent());
                    return handleResult;
                }
                if(helpRecordData.getKilledUserId() == -1){
                    //协助已过期
                    handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HELP_RECORD_NO_FOUND);
                    //清理事件
                    userData.setEvent(new DouLuoDaLuUserEvent());
                    return handleResult;
                }
                if(helpRecordData.getKilledUserId() > 0){
                    //已被击杀
                    handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                    //清理事件
                    userData.setEvent(new DouLuoDaLuUserEvent());
                    return handleResult;
                }

                totalBlood = helpRecordData.getTargetTotalBlood();
                handleResult.setEventId(event.getEventId());

                //伤害计算
                context.getActivity().attackDamage(attack, helpRecordData.getTargetBlood(), handleResult);
                //更新血量与CD
                helpRecordData.setTargetBlood(handleResult.getBlood());
                long now = System.currentTimeMillis();
                handleResult.setTime(DateHelper.getCurrentSecond());
                CrossDouLuoDaLuMgr.updateAttackInfo(context.getUserData(), helpRecordData, handleResult.getDamage(), handleResult.getTime());

                if(handleResult.isKill()){
                    CrossDouLuoDaLuMgr.calBattleReward(hunHuan, goodsProperty, context, regionInfo, eventInfo,null);
                    //被击杀，取消协助，清理事件
                    CrossDouLuoDaLuMgr.updateHelpDataKillInfo(helpRecordData, userData.getUserId(), now , userData);
                    helpRecordData.setHunHuan(PropertyHelper.parsePropertyToString(hunHuan));
                    helpRecordData.setReward(PropertyHelper.parsePropertyToString(goodsProperty));
                    userData.setEvent(new DouLuoDaLuUserEvent());
                }else {
                    event.setAttackTime(handleResult.getTime());
                    event.setBlood(handleResult.getBlood());
                }

            }else {
                //攻击未标记过
                totalBlood = event.getTotalBlood();
                handleResult.setEventId(event.getEventId());

                if(event.getStatus() == 0){
                    event.setStatus(1);
                }

                //伤害计算
                context.getActivity().attackDamage(attack, event.getBlood(), handleResult);

                if(handleResult.isKill()){
                    CrossDouLuoDaLuMgr.calBattleReward(hunHuan, goodsProperty, context, regionInfo, eventInfo,null);
                    //被击杀，清理事件
                    userData.setEvent(new DouLuoDaLuUserEvent());
                }else {
                    event.setAttackTime(DateHelper.getCurrentSecond());
                    event.setBlood(handleResult.getBlood());
                }

            }

            //奖励处理
            dealAttackReward(handleResult, context, totalBlood, hunHuan, goodsProperty);

            if(handleResult.isKill()) {
                //森林日志
                if (eventInfo.isShowLog()) {
                    context.getActivity().addEventNotice(context.getUserData(), eventInfo, event.getMonsterId(), handleResult.getHunHuan(), "", null, null, 1, null);
                }

                //击杀日志
                CrossAutoLogMgr.add(new LogDouLuoDaLuKill(context.getActivityId(), context.getUserId(), context.getUserData().getRegionId(),
                        1, event.getMonsterId(), handleResult.getDamage(), 0, 0, event.getAddTime(), DateHelper.getCurrentSecond()));

                //魂环日志
                CrossAutoLogMgr.add(new LogDouLuoDaLuHunHuan(context.getActivityId(), context.getUserId(), 1, event.getRegionId(), PropertyHelper.parsePropertyToString(hunHuan), 1, event.getMonsterId()));
            }

        }else if(action == 2){

            if(event != context.getUserData().getEvent() || event.getRegionId() != context.getUserData().getRegionId()){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_PLAYER_NOT_IN_REGION);
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }

            //标记魂兽
            event.setStatus(2);
            userData.setUpdateOption();

            DouLuoDaLuHelpRecordData oldMark = userData.getCurrentHelpRecordData();
            //产生协助记录
            DouLuoDaLuHelpRecordData newMark = buildHelpRecordData(event, userData.getRegionId(), event.getTotalBlood(), event.getBlood(), event.getMonsterId(), event.getAddTime());

            CrossDouLuoDaLuMgr.updateAttackInfo(context.getUserData(), newMark, event.getTotalBlood() - event.getBlood(), event.getAttackTime());

            replaceHelpRecord(userData, oldMark, newMark);

            //context.getActivity().broadcastHelpRecordAttackInfo(context.getTeamData());
            context.getActivity().checkUserRedHot(userData, context.getTeamData());
        }else if(action == 3){
            //绕过
            //清除事件
            userData.setEvent(new DouLuoDaLuUserEvent());
        }
        return handleResult;
    }

}
